library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.1.3
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.5     v purrr   0.3.4
## v tibble  3.1.6     v dplyr   1.0.8
## v tidyr   1.2.0     v stringr 1.4.0
## v readr   2.1.2     v forcats 0.5.1
## Warning: package 'dplyr' was built under R version 4.1.3
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout

3D plots

Interactivity comes in really useful when you have more to plot. Adding the third axis is very straightforward, you may simply add a z attribute to plot_ly(). In the plot below, you can clearly see three clusters of iris species.

p <- iris |>
  plot_ly(
    x = ~Sepal.Length,
    y = ~Petal.Length,
    z = ~Petal.Width,
    marker = list(size = 5)
  ) |>
  add_markers(color = ~Species)

p

Plotly enables us to rotate, zoom in/out, and check the coordinates of datapoints. This is something two dimensional non-interactive plots cannot do, and thus Ploly stands as one of the best options when it comes to three dimensional plots.

For other types of 3d plots, you may refer to the Plotly Graphing library1. and look for the appropriate trace functions.

Axes

In 3d plots, axes are embedded in the scene() object, still inside the layout() function. So directly putting xaxis = list(title = "x") does not work. Below is an example of how to use scene object. Note that the title and legend are outside of scene object.

p |>
  layout(
    # main title 
    title = "Iris Species",
    # legend 
    legend = list(
      title = list(text = "<b> Species <b>"),
      itemsizing = "constant"
    ),
    # add titles for three axes
    scene = list(
      xaxis = list(title = "Sepal Length (cm)"),
      yaxis = list(title = "Petal Length (cm)"),
      zaxis = list(title = "Petal Width (cm)")
      )
  )

  1. https://plotly.com/python/3d-charts/ Accessed on 8/4/2022↩︎